<template>
  <div id="app">
    <img alt="" src="./assets/22.jpg" />
    <div class="filling"></div>
    <!-- @click="wxpay()" -->
    <button class="registerNow " @click="dialogVisible = true">
      立即报名
    </button>

    <el-dialog title="资料填写" :visible.sync="dialogVisible" width="90%">
      <el-form :model="list" :rules="rules">
        <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
          <el-input v-model="list.name" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" prop="coNm">
          <el-input v-model="list.coNm" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="公司" :label-width="formLabelWidth" prop="phn">
          <el-input v-model="list.phn" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="职务" :label-width="formLabelWidth" prop="pos">
          <el-input v-model="list.pos" autocomplete="off" clearable></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="queding()">确 定</el-button>
      </span>
    </el-dialog>
    <audio controls autoplay="autoplay" loop="true" id="audio" hidden="hidden">
      <source src="./assets/bgm.mp3" type="audio/mp3" />
      <source src="./assets/bgm.mp3" type="audio/ogg" />
      <embed height="50px" width="100px" src="./assets/bgm.mp3" />
    </audio>
  </div>
</template>
<script
  type="text/javascript"
  src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"
></script>
<script>
// $("html").on("click", function() {
//   audio.play();
// });
</script>

<script>
export default {

  name: "App",
  data() {
    return {
      rules: {
        coNm: [
          { required: true, message: "不能为空", trigger: "blur" },
          { min: 11, max: 11, message: "长度在 11个字符", trigger: "blur" },
        ],
        phn: [{ required: true, message: "不能为空", trigger: "blur" }],
        name: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
          },
        ],
        pos: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
          },
        ],
      },
      orderId: "",
      myOrder: [],
      stuOrder: [],
      code: "",
      url: "",
      minutes: 15,
      seconds: 0,
      openid: "",
      order_money: 0,
      order_number: 0,
      dialogVisible: false,
      username: "",
      username1: "",
      //
      list: {
        name: "",
        phn: "",
        coNm: "",
        pos: "",
      },
      formLabelWidth: "50px",
      yuming: "",
    };
  },

  created() {
    document.addEventListener("touchstart", function() {
      function audioAutoPlay() {
        var audio = document.getElementById("audio");
        audio.play();
      }
      audioAutoPlay();
    });
    let me = this;
    if (location.href.indexOf("code=") === -1) {
      console.log("空白");
    } else {
      me.wxpay();
    }
  },
  methods: {
    queding() {
      console.log(this.list.name);
      console.log(this.list.phn);
      console.log(this.list.coNm);
      console.log(this.list.pos);
      if (
        this.list.name == "" ||
        this.list.phn == "" ||
        this.list.coNm.length !== 11 ||
        this.list.pos == ""
      ) {
        return false;
      }
      var _this = this;
      this.dialogVisible = false;
      this.yuming = document.domain;
      this.$axios
        .post(
          "api/wxpay/line_info",
          {
            yuming: this.yuming,
            name: this.list.name,
            phn: this.list.phn,
            coNm: this.list.coNm,
            pos: this.list.pos,
          },
          { emulateJSON: true }
        )
        .then((kun) => {
          console.log("kun: ", kun);
          console.log("kun.data.lid: ", kun.data.lid);
          if (kun.data.code === 1) {
            _this.username1 = kun.data.lid;
            setTimeout(() => {
              _this.wxpay();
            }, 500);
          } else {
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    //订单支付成功 更新数据
    payOrderMoney() {
      let me = this;
      this.$axios
        .post(
          "api/wxpay/user_code",
          {
            openid: this.openid,
            number: this.order_money,
            money: this.order_number,
          },
          { emulateJSON: true }
        )
        .then((kun) => {
          console.log(kun);
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    // 截取code
    GetUrlParame(parameName) {
      /// 获取地址栏指定参数的值
      /// <param name="parameName">参数名</param>
      // 获取url中跟在问号后面的部分
      var parames = window.location.search;
      // 检测参数是否存在
      if (parames.indexOf(parameName) > -1) {
        var parameValue = "";
        parameValue = parames.substring(
          parames.indexOf(parameName),
          parames.length
        );
        // 检测后面是否还有参数
        if (parameValue.indexOf("&") > -1) {
          // 去除后面多余的参数, 得到最终 parameName=parameValue 形式的值
          parameValue = parameValue.substring(0, parameValue.indexOf("&"));
          // 去掉参数名, 得到最终纯值字符串
          parameValue = parameValue.replace(parameName + "=", "");
          return parameValue;
        }
        return "";
      }
    },
    wxpay() {
      //微信支付 获取code
      // alert("进入");
      var href = location.href;
      if (href.indexOf("code=") === -1) {
        //如果没有code参数就直接调用授权函数
        this.get_weixin_code_login(); //调用授权函数
      } else {
        var local = window.location.href;

        //如果有拿取code值
        this.getUrlCode();
        console.log(local);
        this.code = this.GetUrlParame("code");
        if (this.code == null || this.code == "" || this.code == "undefined") {
          window.location.href = this.url;
        }
        var result = local.split("state=")[1];
        var username = result.split("&connect")[0];
        this.getWxUserInfo(this.code, username);
      }
    },
    get_weixin_code_login() {
      var uri = window.location.href;
      var appid = "wx2bb24f4d34a09668"; //自己公众号的appid
      this.yuming = document.domain;

      var url =
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
        appid +
        "&redirect_uri=http://zf.qianjitianxia.com&response_type=code&scope=snsapi_userinfo&state=" +
        this.username1 +
        "#wechat_redirect";

      window.location.href = url;
      this.url = url;
      // 这里走完就是已经授权了。如果授权了就会url中带有code
    },
    getUrlCode() {
      //获取url参数
      var url = location.search;
      this.winUrl = url;
      var theRequest = new Object();
      if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        var strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
          theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
        }
      }
      return theRequest;
    },
    getWxUserInfo(code, name) {
      //授权后获取用户的基本信息
      let me = this;

      console.log("授权码" + code);
      this.$axios
        .post(
          "api/wxpay/get_signature",

          // { code: code, oid: this.orderId, uid: localStorage.uid },

          {
            code: code,
            lid: name,
          },
          { emulateJSON: true }
        )
        .then((kun) => {
          console.log(kun);
          var kun = kun.data;
          // alert("支付参数" + kun);

          if (typeof WeixinJSBridge == "undefined") {
            if (document.addEventListener) {
              document.addEventListener(
                "WeixinJSBridgeReady",
                me.onBridgeReady,
                false
              );
            } else if (document.attachEvent) {
              document.attachEvent("WeixinJSBridgeReady", me.onBridgeReady);
              document.attachEvent("onWeixinJSBridgeReady", me.onBridgeReady);
            }
          } else {
            //订单创建成功返回支付参数和order_id便于前端唤起支付
            console.log("唤起支付" + kun.appId);
            // alert("唤起支付" + kun.appId);

            this.openid = kun.openid;
            this.order_money = kun.order_money;
            this.order_number = kun.order_number;

            me.onBridgeReady(
              kun.appId,
              kun.timeStamp,
              kun.nonceStr,
              kun.package,
              kun.paySign,
              kun.signType
            );
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },

    // 支付
    onBridgeReady(appid, time, nonceStr, prepay_id, paySign, trade_type) {
      let me = this;
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: appid, // 公众号名称，由商户传入
          timeStamp: time, // 时间戳，自1970年以来的秒数
          nonceStr: nonceStr, // 随机串
          package: prepay_id, // 统一下单接口返回的prepay_id参数值
          signType: trade_type, // 微信签名方式：
          paySign: paySign, // 微信签名
        },
        function(res) {
          console.log(res);
          // alert(order_id);
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            // 使用以上方式判断前端返回,微信团队郑重提示：
            me.$message({
              message: "支付成功",
              type: "success",
            });
            // console.log("支付成功");
            // me.payOrderMoney(openid, order_money, order_number);
            // me.payOrderMoney();

            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
            me.$message({
              message: "支付过程中用户取消",
              type: "warning",
            });
          } else if (res.err_msg == "get_brand_wcpay_request:fail") {
            me.$message.error("支付失败");
          } else {
            console.log(res);
          }
        }
      );
    },
  },
};
</script>

<style>
.el-dialog__footer {
  text-align: center !important;
}
.el-dialog__footer button {
  width: 60vw;
}
.el-dialog__body {
  /* padding-bottom: 0; */
}
.filling {
  height: 100px;
  background-color: #fff;
}
img {
  width: 100vw;
}
.registerNow {
  width: 70vw;
  height: 80px;
  border-radius: 50px;
  position: fixed;
  bottom: 8px;
  left: 50%;
  text-align: center;
  transform: translateX(-50%);
  /* letter-spacing: 20px; */
  font-size: 35px;
  font-weight: 700;
  color: #fff;
  background-color: #de2ba3;
  border: none;
}
.el-input {
  width: 90% !important;
}
.el-form-item__label {
  width: 69px !important;
}
</style>
